package cn.com.cetccst.location;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

public class LocationUtil {
    private static final String TAG = "LocationUtil";
    private static final double EMPTY_LOCATION = 0;

    public static boolean isValidLocation(double latitude, double longitude) {
        return latitude != EMPTY_LOCATION && longitude != EMPTY_LOCATION;
    }

    public static boolean isLocationServiceEnabled(Context context) {
        try {
            int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            boolean isLocationEnabled = locationMode != Settings.Secure.LOCATION_MODE_OFF;
            Log.i(TAG, "location mode is " + locationMode);
            return isLocationEnabled;
        } catch (Settings.SettingNotFoundException e) {
            Log.i(TAG, "location setting is not found", e);
            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                boolean isLocationEnabled = locationManager.isLocationEnabled();
                Log.i(TAG, "locationManager enabled: " + isLocationEnabled);
                return isLocationEnabled;
            }
        }
        return false;
    }

    public static boolean isAlwaysPermissionGranted(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            return context.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    public static boolean isFlightModeEnabled(Context context) {
        int airplaneMode = Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0);
        boolean isAirplaneModeEnabled = airplaneMode != 0;
        Log.i(TAG, "airplane mode is " + isAirplaneModeEnabled);
        return isAirplaneModeEnabled;
    }
}
